<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends AdminController {

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        $username       =   I('nickname');
        if(is_numeric($username)){
            $map['id|username'] = array(intval($username),array('like','%'.$username.'%'),'_multi'=>true);
        }else{
            $map['username']    = array('like', '%'.(string)$username.'%');
        }
        $map['id'] = array('neq',1);
        $map['user_type']=2;
        $list   = $this->lists('ucenter_member', $map,'reg_time desc');
        foreach($list as &$li){
            $member = M('member')->where('uid='.$li['id'])->find();
          //  $li['avatar_url'] =M('picture')->where('id='.$member['avatar'])->getField('path');
            $li['avatar_url'] =$member['avatar'];
            $li['nickname'] = $member['nickname'];
            $li['amount'] = $member['amount'];
            $li['coin'] = $member['coin'];
            $li['login'] = $member['login'];
            $li['status'] = $member['status'];
            if($member['is_exchange']){
                $li['permissions'] ="是";
            }else{
                $li['permissions'] ="否";
            }
        }
        int_to_string($list);
        $number  = M('ucenter_member')->where('id !=1')->count();
        $this->assign('number', $number);
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /**
     * 编辑用户信息
     *
     */
    public function edit(){
        $id = I('id');
        $member = D('member')->where('uid='.$id)->find();
        $member['avatar_url'] =$member['avatar'];
        $u_member=M('ucenter_member')->where('id='.$id)->find();
        $member['username'] = $u_member['username'];
        if(IS_POST) {
            $data['avatar'] = I('post.avatar_id');
            $data['nickname'] = I('post.nickname');
            $data['is_exchange'] = I('post.coin_permissions');
            D('member')->where('uid='.$member['uid'])->save($data);
            $this->success('用户信息保存成功！',U('index'));
        }ELSE {
            $member['coin_permissions'] =$member['is_exchange'];
            $this->assign ( 'info', $member );
            $this->meta_title = '用户信息查看修改';
            $this->display ('edit');
        }
    }

    /**
     * 用户详情
     */
    public  function  userDetail(){
        $id = I('id');

        if (empty($id)) {
            $this->error('非法操作');
        }

        $User = D('user');
        $userinfo = $User->getuserDetail($id);
        //收货地址
        $member_receive = $User->getReceive($id);
        //消费记录
        $map['uid'] = $id;
      //  $list = M('user_trade')->where($map)->order('createtime desc')->select();
        $list =$this->lists('user_trade', $map,'createtime desc');
        foreach ($list as $key=>&$li){
            $list[$key]['createtime'] = date('Y-m-d H:i:s', $li['createtime']);
            if($li['type'] == 1){
                $list[$key]['type_txt'] = "充值";
                $list[$key]['money'] = "+".$li['money'];
            }else  if($li['type'] == 2){
                $list[$key]['type_txt'] = "下注";
                $list[$key]['money'] = "-".$li['money'];
            }else  if($li['type'] == 3){
                $list[$key]['type_txt'] = "中奖";
                $list[$key]['money'] = "+".$li['money'];
            }else  if($li['type'] == 4){
                $list[$key]['type_txt'] = "兑换商品";
                $list[$key]['money'] = "-".$li['money'];
            }else  if($li['type'] == 5){
                $list[$key]['type_txt'] = "推广";
                $list[$key]['money'] = "+".$li['money'];
            }else  if($li['type'] == 6){
                $list[$key]['type_txt'] = "转增";
                $list[$key]['money'] = "-".$li['money'];
            }else  if($li['type'] == 7){
                $list[$key]['type_txt'] = "获赠";
                $list[$key]['money'] = "+".$li['money'];
            }
        }
        //赠送记录
        $c_map['uid']= $id;
        $coin_list = M('giverecord')->where($c_map)->order('uptime desc')->select();
        foreach ($coin_list as &$coin){
            if($coin['money_type']==1) {
                if ($coin['type'] == 1) {
                    $msg = "你赠送给ID为" . $coin['touid'] . "的用户" . $coin['num'] . "个元宝";
                } else if ($coin['type'] == 2) {
                    $msg = "你收到了ID为" . $coin['touid'] . "的用户" . $coin['num'] . "个元宝";
                }
            }else if($coin['money_type']==2){
                if($coin['type'] ==1){
                    $msg = "你赠送给ID为".$coin['touid']."的用户".$coin['num']."个惠Go币";
                }else if($coin['type'] ==2){
                    $msg = "你收到了ID为".$coin['touid']."的用户".$coin['num']."个惠Go币";
                }
            }
            $coin['uptime'] =date('Y/m/d H:i', $coin['uptime']) ;
            $coin['msg'] = $msg;
        }
        $this->assign('coin_list', $coin_list);

        //邀请好友明细
        $uid = $id;
        $map['type'] = 5;
        $map['status'] = 1;
        $map['uid'] = $uid;
        $invitation = M('user_trade')->where($map)->field('sum(money) as money,b_refer')->order('createtime desc')->group('b_refer')->select();
        //echo  M('user_trade')->getLastSql();
        foreach ($invitation as &$inv){
            $avatar=M('member')->where('uid='.$inv['b_refer'])->getField('avatar');
            $inv['avatar'] =  $avatar?$avatar:'';
        }
        $inv_count =M('user_trade')->where($map)->group('b_refer')->select();
        $summoney =M('user_trade')->where($map)->sum('money');
        $result['my_inv']=$invitation?$invitation:array();
        $result['inv_count']= count($inv_count);
        $result['summoney'] = $summoney?$summoney:0;
        $this->assign('receive', $result);

        $this->assign('member_receive', $member_receive);
        $this->assign('userInfo', $userinfo);
        $this->assign('list', $list);
        $this->meta_title = '用户详情';
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $this->assign('nickname', $nickname);
        $this->meta_title = '修改昵称';
        $this->display();
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User   =   new UserApi();
        $uid    =   $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member =   D('Member');
        $data   =   $Member->create(array('nickname'=>$nickname));
        if(!$data){
            $this->error($Member->getError());
        }

        $res = $Member->where(array('uid'=>$uid))->save($data);

        if($res){
            $user               =   session('user_auth');
            $user['username']   =   $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $this->success('修改昵称成功！');
        }else{
            $this->error('修改昵称失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
        $this->meta_title = '修改密码';
        $this->display();
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword(){
        //获取参数
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api    =   new UserApi();
        $res    =   $Api->updateInfo(UID, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            $this->error($res['info']);
        }
    }

    /**
     * 用户行为列表
     * @author huajie <banhuajie@163.com>
     */
    public function action(){
        //获取列表数据
        $Action =   M('Action')->where(array('status'=>array('gt',-1)));
        $list   =   $this->lists($Action);
        int_to_string($list);
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);

        $this->assign('_list', $list);
        $this->meta_title = '用户行为';
        $this->display();
    }

    /**
     * 新增行为
     * @author huajie <banhuajie@163.com>
     */
    public function addAction(){
        $this->meta_title = '新增行为';
        $this->assign('data',null);
        $this->display('editaction');
    }

    /**
     * 编辑行为
     * @author huajie <banhuajie@163.com>
     */
    public function editAction(){
        $id = I('get.id');
        empty($id) && $this->error('参数不能为空！');
        $data = M('Action')->field(true)->find($id);

        $this->assign('data',$data);
        $this->meta_title = '编辑行为';
        $this->display();
    }

    /**
     * 更新行为
     * @author huajie <banhuajie@163.com>
     */
    public function saveAction(){
        $res = D('Action')->update();
        if(!$res){
            $this->error(D('Action')->getError());
        }else{
            $this->success($res['id']?'更新成功！':'新增成功！', Cookie('__forward__'));
        }
    }

    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('id',0));
        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Member', $map );
                break;
            case 'resumeuser':
                $this->resume('Member', $map );
                break;
            // case 'deleteuser':
            //     $this->delete('Member', $map );
            //     M('ucenter_member')->delete('ucenter_member', $map );
            //     break;
            default:
                $this->error('参数非法');
        }
    }

    /**
     * 删除用户
     * @param string $uid
     */
    public function delete($uid){
    	$uid=I('uid');
    	M('member')->where('uid='.$uid)->delete();
    	M('ucenter_member')->where('id='.$uid)->delete();

    	$this->success('用户删除成功',U('index'));
    }

    public function add($username = '', $password = '', $repassword = '', $email = ''){
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password, $username);
            if(0 < $uid){ //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                if(!M('Member')->add($user)){
                    $this->error('用户添加失败！');
                } else {
                    $this->success('用户添加成功！',U('index'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $this->meta_title = '新增用户';
            $this->display();
        }
    }
    
    public function referrer() {
        $nickname       =   I('nickname');
        $map['status']  =   array('egt',0);
        if(is_numeric($nickname)){
            $map['uid|nickname']=   array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true);
        }else{
            $map['nickname']    =   array('like', '%'.(string)$nickname.'%');
        }
        $uids = M('member')->where($map)->select();
        $uid_arr = array();
        if (!empty($uids)) {
            foreach ($uids as $key => $value) {
                $uid_arr[] = $value['uid'];
            }
        }
        $where = array('referrer'=> array('in', $uid_arr));
        $list = $this->lists('member', $where);
        $this->assign('_list', $list);
        $this->meta_title = '推荐用户';
        $this->display();
    }

    /**
     * 异步获取用户数据
     *
     * @param string query 用户编号或昵称
     * @return array 用户ID及昵称
     */
    public function autocomplete(){
        $username       =   I('query');
        $map['status']  =   array('egt',0);
        if(is_numeric($username)){
            $map['id|username']=   array(intval($username),array('like','%'.$username.'%'),'_multi'=>true);
        }else{
            $map['username']    =   array('like', '%'.(string)$username.'%');
        }

        $list   = M('ucenter_member')->where($map)->page(0, 5)->select();

        echo json_encode($list);
    }

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

    /**
     * 虚拟用户列表
     */
    public function virtualList(){
        $map['user_type']=3;
        $list   = $this->lists('ucenter_member',$map,'reg_time desc');
        foreach($list as &$li){
            $member = M('member')->where('uid='.$li['id'])->find();
            $li['avatar_url'] =$member['avatar'];
            $li['nickname'] = $member['nickname'];
            $li['day_bet_total'] = $member['day_bet_total'];
            $li['night_bet_total'] = $member['night_bet_total'];
            $li['status'] = $member['status'];
        }
        int_to_string($list);
        $number  = M('ucenter_member')->where('id !=1')->count();
        $this->assign('number', $number);
        $this->assign('_list', $list);
        $this->meta_title = '虚拟用户信息';
        $this->display();
    }

    /**
     * 添加虚拟用户
     */
    public function addVirtual(){
        if(IS_POST){
            $post =I('');
            $avatar =M('picture')->where('id='.$post['avatar_id'])->getField('path');
            if($avatar){
                $avatar = C('BASE_URI') . $avatar;
            }else{
                $avatar = '';
            }

            $data_ucenter['username'] = $post['username'];
            $data_ucenter['password'] =md5(sha1('123456') . UC_AUTH_KEY);
            $data_ucenter['reg_time'] = time();
            $data_ucenter['reg_ip'] =get_client_ip(1);
            $data_ucenter['last_login_time'] =time();
            $data_ucenter['last_login_ip'] =get_client_ip(1);
            $data_ucenter['status'] =1;
            $data_ucenter['user_type'] = 3;
            $uid=M('ucenter_member')->add($data_ucenter);
            $data_member['uid'] = $uid;
            $data_member['nickname'] = $post['nickname'];
            $data_member['avatar'] = $avatar;
            $data_member['reg_time'] = time();
            $data_member['status'] =1;
            $data_member['day_bet_total']   =  $post['day_bet_total'];
            $data_member['night_bet_total'] = $post['night_bet_total'];
            $result = M('member')->add($data_member);
            if(!$result){
                $this->error('虚拟用户添加失败！');
            } else {
                $this->success('虚拟用户添加成功！',U('virtualList'));
            }
                var_dump($post);
        }
        $this->display();
    }

    /**
     * 编辑虚拟用户
     */
    public function editVirtual(){
        $id = I('id');
        $member = M('member')->where('uid='.$id)->find();
        $member['avatar_url'] =$member['avatar'];

        $u_member=M('ucenter_member')->where('id='.$id)->find();
        if(IS_POST) {
            $avatar_id=I('post.avatar_id');
            if(is_numeric($avatar_id)){
                $avatar =M('picture')->where('id='.I('post.avatar_id'))->getField('path');
                if($avatar){
                    $avatar = C('BASE_URI') . $avatar;
                }else{
                    $avatar = '';
                }
            }else{
                $avatar=$avatar_id;
            }


            M('ucenter_member')->where('id='.$id)->Save(array(
                'username' => I('post.username')));
            D('member')->where('uid='.$member['uid'])->Save(array(
                'avatar' => $avatar,
                'nickname' => I('post.nickname'),
                 'day_bet_total' => I('post.day_bet_total'),
                 'night_bet_total' => I('post.night_bet_total'),
                 'update_time' => time()
            ));
            $this->success('用户信息保存成功！',U('virtualList'));
        }ELSE {
            $member['username'] = $u_member['username'];
            $this->assign ( 'info', $member );
            $this->meta_title = '用户信息查看修改';
            $this->display ('editVirtual');
        }
    }

    /**
     * 删除虚拟用户
     */
    public function delVirtual(){
        $uid=I('uid');
        M('member')->where('uid='.$uid)->delete();
        M('ucenter_member')->where('id='.$uid)->delete();

        $this->success('用户删除成功',U('virtualList'));
    }



    /**
     * 动物列表用户下注量
     */
    public function animalList(){
        $list = $this->lists('animal', '','id asc');
        $this->assign('_list', $list);
        $this->meta_title = '动物设置';
        $this->display();
    }

    /**
     * 动物设置用户下注量
     */
    public function animalEdit(){
        $id = I('id');
        $animal = D('animal')->where('id='.$id)->find();
        if(IS_POST) {
            $data['user_total'] = I('user_total');
            $data['uptime'] =time();
            $result = M('animal')->where('id='.$id)->save($data);
            if($result){
                $this->success('修改成功！',U('animalList'));
            }else{
                $this->error('修改失败！');
            }
        }
        $this->assign ( 'info', $animal);
        $this->display ();
    }

    /**
     * 邀请关系
     */
    public function invitation(){

        $uid = I('uid');
        if (!empty($uid)) {
            $map['uid'] = $uid;
        }

        $map['type'] = 5;
        $map['status'] = 1;
        $invitation = M('user_trade')->where($map)->field('uid,sum(money) as money,b_refer')->order('createtime desc')->group('b_refer')->select();
        //echo M('user_trade')->getLastSql();
        foreach ($invitation as &$inv){
            $avatar=M('member')->where('uid='.$inv['b_refer'])->getField('avatar');
            $inv['avatar'] =  $avatar?$avatar:'';
        }
        $inv_count =M('user_trade')->where($map)->group('b_refer')->select();
        $summoney =M('user_trade')->where($map)->sum('money');
        $this->assign ('_list', $invitation);
        $this->assign ('inv_count', count($inv_count));
        $this->assign ('summoney', $summoney);
        $this->display ();
    }




}
